package com.le.tester.javaThink.fourth.concurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2021/11/2 17:04
 * description：大门统计进入的人数
 */
class Count {
    private int count = 0;
    private Random random = new Random(47);


    //先调用了递增，再调用了value
    public synchronized int increment() {
        int temp = count;
        if (random.nextBoolean()) {
            //synchronized是否和yield会冲突
            Thread.yield();
        }
        return count = ++temp;
    }

    public synchronized int value() {
        return count;
    }
}

class Entrance implements Runnable {

    private static Count count = new Count();

    private static List<Entrance> entrances = new ArrayList<>();

    private int number = 0;

    private final int id;

    private static volatile boolean canceled = false;

    public static void cancel() {
        canceled = true;

    }

    public Entrance(int id) {
        this.id = id;
        entrances.add(this);
    }

    @Override
    public void run() {
        while (!canceled) {
            synchronized (this) {
                ++number;
            }
            System.out.println(this + " Total: " + count.increment());
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                System.out.println("sleep interrupted");
            }
        }
        System.out.println("Stopping" + this);
    }

    public synchronized int getValue() {
        return number;
    }

    @Override
    public String toString() {
        return "Entrance{" +
                "number=" + number +
                ", id:" + id + ":" + getValue() +
                '}';
    }

    public static int getTotalCount() {
        return count.value();
    }

    public static int sumEntrances() {
        int sum = 0;
        for (Entrance entrance : entrances) {
            sum += entrance.getValue();
        }
        return sum;
    }
}

public class OrnamentalGarden {
    public static void main(String[] args) throws Exception {
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++)
            service.submit(new Entrance(i));
        TimeUnit.SECONDS.sleep(3);
        Entrance.cancel();
        service.shutdown();
        if (service.awaitTermination(250, TimeUnit.MILLISECONDS))
            System.out.println("some tasks were not terminated!");
        System.out.println("Total is " + Entrance.getTotalCount());
        System.out.println("sum of Entrances:" + Entrance.sumEntrances());
    }

}
